<template>
	<view class="body">
		<!-- 搜索好友 -->
		<view class="search">
			<u-search placeholder="请输入好友id" v-model="keyword" :showAction="false" @search="search"></u-search>
		</view>
		<view class="system">
			<view class="system-nav" @click="systemchlick">
				<u-avatar shape="square" size="35" icon="volume" fontSize="26" bgColor="#448aca"></u-avatar>
				<text class="system-text">系统消息</text>
			</view>
			<view class="box" v-if="noReadSystemNum > 0">
			 <u-badge numberType="overflow" type="error" max="99" :value="noReadSystemNum"></u-badge>
			</view>
			<u-line margin="10px 0px 0px 0px" hairline="true"></u-line>
		</view>
		<view class="ordermsg">
			<view class="ordermsg-nav" @click="ordermsgchlick">
				<u-avatar shape="square" size="35" icon="bell" fontSize="26" bgColor="#7ccabb"></u-avatar>
				<text class="ordermsg-text">通知消息</text>
			</view>
			<view class="box" v-if="ordermsgnum > 0">
			 <u-badge numberType="overflow" type="error" max="99" :value="ordermsgnum"></u-badge>
			</view>
			<u-line margin="10px 0px 0px 0px" hairline="true"></u-line>
		</view> 
		<view class="user">
			<view class="user-nav" @click="userchlick">
				<u-avatar shape="square" size="35" icon="man-add-fill" fontSize="26" bgColor="#50f3af"></u-avatar>
				<text class="user-text">新的朋友</text>
			</view>
			<view class="box" v-if="addUserMessageNum > 0">
			 <u-badge numberType="overflow" type="error" max="99" :value="addUserMessageNum"></u-badge>
			</view>
			<u-line margin="10px 0px 0px 0px" hairline="true"></u-line>
		</view>
		<!-- 好友列表分割线-->
		<view class="user-divider">
			<u-divider text="好友列表"></u-divider> 
		</view>
		<!-- 陌生人列表信息 -->
		<view class="userlist" v-if="islogin" v-for="(item1) in UserList" :key="item1.id">
			<view class="userlist-nav" @touchstart="touchstartE1()" @touchend="touchendE1(item1)" v-if="item1.isStranger">
				<u-avatar class="img-avatar" shape="square" size="35" :src="item1.img" fontSize="26"></u-avatar>
				<text class="userlist-text">{{item1.name}}</text>
				<text class="tip" >(陌生人)</text>
				<!-- 获取最后一条消息 -->
				<text class="indexmessage" v-if="item1.lastmessage != null">{{item1.lastmessage}}</text>
				<u-line margin="10px 0px 0px 0px" hairline="true"></u-line>
			</view>
			<!-- 用户消息提示图标 -->
			<view class="box" v-if="item1.totalMessage > 0 & item1.isStranger" >  
			 <u-badge numberType="overflow" type="error" max="99" :value="item1.totalMessage"></u-badge>  
			</view>
		</view>
		
		<!-- 加载好友列表 -->
		<view class="userlist" v-if="islogin" v-for="(item) in UserList" :key="item.id"> 
			<view class="userlist-nav" @touchstart="touchstartE()" @touchend="touchendE(item)" v-if="! item.isStranger">
				<u-avatar class="img-avatar" shape="square" size="35" :src="item.img" fontSize="26"></u-avatar>
				<text class="userlist-text">{{item.name}}</text> 
				<text class="tip1" >(好友)</text>
				<!-- 获取最后一条消息 -->
				<text class="indexmessage" v-if="item.lastmessage != null">{{item.lastmessage}}</text>
			</view>
			<!-- 用户消息提示图标 -->
			<view class="box" v-if="item.totalMessage > 0 & ! item.isStranger ">  
			 <u-badge numberType="overflow" type="error" max="99" :value="item.totalMessage"></u-badge>  
			</view>
			<u-line margin="10px 0px 0px 0px" hairline="true"></u-line>
		</view>
		<view class="loading" >
			<u-loadmore :status="status" :line="line" :nomoreText="nomoreText" /> 
		</view>
		<view class="adduser">
			<u-modal :show="show" :title="title" :content='content' confirmText='添加好友' :closeOnClickOverlay="true" :showCancelButton="true" @cancel="cancel" @confirm="confirm" @close="close">
				<view class="cart">
					<view class="userimg">
						<u-avatar shape="circle" size="80" :src="userInfo.img" fontSize="26"></u-avatar>
					</view>
					<view class="username">
						<text>{{userInfo.name}}</text>
					</view>
					<view class="state">
						<text>状态:</text>
						<text style="margin-left: 4rpx; color: #00ff7f;" v-if="userInfo.state == 0">正常</text>
						<text style="margin-left: 4rpx; color: red;" v-if="userInfo.state == 1">锁定</text>
					</view>
				</view>
			</u-modal>
		</view>
	</view>
</template>

<script>
	import {http} from "../static/service/requestAddress/rtas.js"
	const app = getApp()
	export default {
		data() {  
			return {
				keyword:"",
				show:false,
				title:"好友信息",
				userInfo:{ //用户信息
					
				},
				content:"",
				total:0,
				SystemValue:1,
				UserValue:2,
				islogin:false,//是否登录标记
				userid :"", //登录用户id
				clickOrlongtap:false,//判读用户是点击还是长按
				UserList:[],//用户好友列表
				touchT: '', // 触屏开始时间
				touchE: '', // 触屏结束时间
				systemList:[],//系统消息
				noReadSystemNum:0,//未读系统消息数
				userMessageList:[],//用户消息
				noReadUserMessageListNum:0,//未读用户消息数
				offlineUserMessage:[],//用户离线消息集合
				addUserMessage:[],//添加好友的消息
				addUserMessageNum:0,//添加好友信息总合
				ordermsgnum:0,//订单消息数量
				message:{
					
				},
				status: "nomore",//"loading",
				line:true,
				nomoreText:"没有更多了",
			}
		},
		created(){
			uni.$on("usermessage",res=>{
					//更新消息缓存
					var userlist = JSON.parse(uni.getStorageSync("userfriendlist"))
					for(var i = 0;i<userlist.length;i++){
						if(userlist[i].id == res.sendUser){
							userlist[i].lastmessage = res.messagecontent
							userlist[i].totalMessage += 1
						} 
					} 
					this.UserList = userlist
					uni.setStorageSync("userfriendlist",JSON.stringify(userlist))
					var num = uni.getStorageSync("tabbar")
					uni.setTabBarBadge({ //显示数字
						index: 1, //tabbar下标
						text:""+num,//数字
						success() {
						console.log("消息设置成功") 
						},
						fail(e){ 
							 console.log("设置失败"+JSON.stringify(e))
						}
					})
			})
			//监听系统消息事件
			uni.$on("system",res=>{
				var systemlist = JSON.parse(uni.getStorageSync("system"))
				var num = 0
				for(var i = 0;i<systemlist.length;i++){
					//遍历未读消息
					if(systemlist[i].isRead == false){
						num += 1
					}
				}
				 this.noReadSystemNum = num
			})
			//监听订单通知事件
			uni.$on("ordermsg",res=>{
				var ordermsg = JSON.parse(uni.getStorageSync("ordermsg"))
				var num = 0
				for(var i = 0;i<ordermsg.length;i++){
					//遍历未读消息
					if(ordermsg[i].read == false){
						num += 1
					}
				}
				 this.ordermsgnum = num
				 console.log("订单通知数量："+this.ordermsgnum)
			})
		},
		onShow() {
			//设置tabbar
			var num = uni.getStorageSync("tabbar")
				if(num > 0){
					uni.setTabBarBadge({ //显示数字
						index: 1, //tabbar下标
						text:""+num,//数字
						success() {
						console.log("消息设置成功") 
						},
						fail(e){ 
						   console.log("设置失败"+JSON.stringify(e))
						}
					})
					this.$forceUpdate()
				}else{
					uni.removeTabBarBadge({
						index:1
					})
				}
			//处理缓存
			if(uni.getStorageSync('user')){
				this.islogin = true
				//获取好友列表
				if(uni.getStorageSync("userfriendlist")){
					this.UserList = JSON.parse(uni.getStorageSync("userfriendlist"))
				}
				//重缓存中加载对应数据
					//加载系统消息
					var system = uni.getStorageSync("system")
					if(system != "" | system.length > 0){
						//对系统消息进行处理
						this.systemList = JSON.parse(system)
						var T = 0
						for(var i = 0;i<this.systemList.length;i++){
							if(this.systemList[i].read == false){
								T += 1
							}
						}
						this.noReadSystemNum = T
					}
					//加载掉线时的好友消息
					var offlineMessage = uni.getStorageSync("offlineUserMessage")
					if(offlineMessage != "" | offlineMessage.length > 0){
						var T = JSON.parse(offlineMessage)
						//遍历掉线时的消息数组
						for(var i = 0;i<T.length;i++){
							//判断是添加好友的信息，还是好友发送的信息,
							if(uni.getStorageSync("addUserMessage")){
								this.addUserMessageNum = JSON.parse(uni.getStorageSync("addUserMessage")).length
							}
							if(T[i].isSystem == 2){ //添加好友信息
								this.addUserMessage.push(T[i])
								this.addUserMessageNum += 1
								//将添加好友消息添加到缓存
								if(uni.getStorageSync("addUserMessage")){
									var a = JSON.parse(uni.getStorageSync("addUserMessage"))
									T[i].isRead = false
									a.push(T[i])
									uni.setStorageSync("addUserMessage",JSON.stringify(a))
								}else{
									var a = []
									T[i].isRead = false
									a.push(T[i])
									uni.setStorageSync("addUserMessage",JSON.stringify(a))
								}
								continue
							}
							//2.是掉线时好友发送的消息的情况
							if(T[i].isSystem == 1){
								var flage = false;//是否是好友发送的消息
								//先查询是否是好友的消息
								for(var j = 0 ;j < this.UserList.length;j++){
									if(this.UserList[j].id == T[i].sendUser){
										this.UserList[j].lastmessage = T[i].messagecontent
										this.UserList[j].totalMessage += 1
										flage = true
										break
									}
								}
								//处理陌生人的消息
								if(! flage){
									//将陌生人添加到好友列表缓存
									var UserFlage = {
										address: null,
										createTime: null,
										id: T[i].sendUser,
										img: T[i].sendUserImg,
										isStranger: true,
										lastmessage: T[i].messagecontent,
										limit: null,
										name: T[i].sendUserName,
										password: null,
										phone: null,
										sex: null,
										state: null,
										totalMessage: 1,
										updateTime: null,
										userFriend: null,
									}
									this.UserList.push(UserFlage)
									//更新好友列表缓存
									uni.setStorageSync("userfriendlist",JSON.stringify(this.UserList))	
								}
								//添加好友消息到缓存
								if(uni.getStorageSync("userMessage")){
									var a = JSON.parse(uni.getStorageSync("userMessage"))
									a.push(T[i])
									uni.setStorageSync("userMessage",JSON.stringify(a))
								}else{
									var a = []
									a.push(T[i])
									uni.setStorageSync("userMessage",JSON.stringify(a))
								}
								//更新好友列表缓存
								uni.setStorageSync("userfriendlist",JSON.stringify(this.UserList))	
							}
							if(T[i].isSystem == 6){
								var flage = []
								var msglist = uni.getStorageSync("ordermsg")
								//缓存为空的情况
								if(msglist.length == 0 | msglist == null){
									console.log("进入订单消息缓存为空的情况")
									T[i].read = false
									flage.push(T[i])
									uni.setStorageSync("ordermsg",JSON.stringify(flage))
								}else{
									console.log("进入订单消息缓存不为空的情况")
									T[i].read = false
									flage = JSON.parse(uni.getStorageSync("ordermsg"))
									flage.push(T[i])
									uni.setStorageSync("ordermsg",JSON.stringify(flage))
								}
								this.ordermsgnum += 1
							}
						}
						//情况离线缓存
						uni.removeStorageSync("offlineUserMessage")
				}else{//没有离线消息的情况
				
					//加载系统消息缓存
					var system = uni.getStorageSync("system")
					if(system != "" | system.length > 0){
						//对系统消息进行处理
						this.systemList = JSON.parse(system)
						var T = 0
						for(var i = 0;i<this.systemList.length;i++){
							if(this.systemList[i].read == false){
								T += 1
							}
						}
						this.noReadSystemNum = T
					}
					//加载添加好友信息缓存
					if(uni.getStorageSync("addUserMessage")){
						console.log("添加前的数:"+this.addUserMessageNum)
						var T = JSON.parse(uni.getStorageSync("addUserMessage"))
						for(var i = 0 ;i < T.length;i++ ){
							if(T[i].isRead == false){
								this.addUserMessageNum += 1
							}
						}
					}
					//订单消息数量
					if(uni.getStorageSync("ordermsg")){
						var T = JSON.parse(uni.getStorageSync("ordermsg"))
						var a = 0
						for(var i = 0 ;i < T.length;i++ ){
							if(T[i].read == false){
								a += 1
							}
						}
						this.ordermsgnum = a
					}
				}
			}
		},
		onHide(){
			//处理用户消息总数
			for(var i = 0;i<this.UserList.length;i++){
				this.UserList[i].totalMessage = 0
			}
			this.addUserMessageNum = 0
			this.ordermsgnum = 0
			this.addUserMessage = []
		},
		//下拉刷新
		onPullDownRefresh() {
			//从新加载好友列表信息到缓存
			this.userlist()
		},
		methods:{
			//搜索好友
			search(){
				if(this.keyword == '' | this.keyword.length < 5){
					uni.$u.toast("id长度不能小于5,不能为空")
					return
				}
				uni.request({
					url:http+"user/userinfo/"+this.keyword,
					method:"GET",
					complete:(res) =>{
						if(res.data.code == 20021){
							this.userInfo = res.data.date
						}else{
							uni.$u.toast("用户不存在")
						}
					}
				})
				console.log(this.keyword)
				this.show = true
			},
			//重新加载好友列表
			userlist(){
				var that = this
				console.log("获取好友列表")
				this.status = "loading"
				const user = uni.getStorageSync('user')
				if(user.length > 0 & user != ""){
					var userid = JSON.parse(user).id
						//从新加载好友列表信息到缓存
						uni.request({
							url:http+"user/getuserlist/"+userid,
							method:"GET",
							complete:(res)=> {
								if(res.data.code == 20021){
									this.UserList = res.data.date
									uni.setStorageSync("userfriendlist",JSON.stringify(res.data.date))
									uni.$u.toast("获取用户列表成功")
									that.$forceUpdate()
								}else{
									uni.$u.toast("获取用户列表失败，请下拉刷新重试")
								}
							}
						})
						this.status = "nomore"
				}else{
					uni.$u.toast("您还未登录，登录后才能获取好友信息喔")
					this.status = "nomore"
				}
			},
			systemchlick(){
				uni.navigateTo({
					url:"/systemMessage/index"+"?system="+uni.getStorageSync("system")
				})
			},
			//订单消息点击事件
			ordermsgchlick(){
				console.log("点击了订单消息通知")
				uni.navigateTo({
					url:"/ordermsg/ordermsgindex" 
				})
			},
			userchlick(){
				uni.navigateTo({
					url:"/addUser/addUserindex"
				})
			},
			userlistchlick(e){
				//tabber消息个数减去对应的数量
				var num = uni.getStorageSync("tabbar")
				console.log("num:"+num +"|"+e.totalMessage)
					num -= e.totalMessage
					console.log("减去后的num"+num)
					if(num <= 0){ 
						uni.removeTabBarBadge({
							index:1 
						})
					}else{
						uni.setTabBarBadge({ //显示数字
							index: 1, //tabbar下标
							text:""+num,//数字
							success() {
							},
							fail(e){ 
							}
						})
						uni.setStorageSync("tabbar",num)
					}
				//清楚用户列表消息提示
				for(var i = 0;i< this.UserList.length;i++){
					if(e.id == this.UserList[i].id){
						var num = this.UserList[i].totalMessage
						this.$set(this.UserList[i],"totalMessage",0)
						//更新缓存
						var str = this.UserList
						uni.setStorageSync("userfriendlist",JSON.stringify(str))
						this.$forceUpdate()
						break
					}
				}
				uni.navigateTo({
					url:"/see/chatpage"+"?id="+e.id+"&name="+e.name+"&img="+e.img
				})
			},
			getmessage(msg){
				console.log(msg)
			},
			longtap(){
				console.log("触发了长按事件")
			},
			//用户触摸屏幕开始时间
			touchstartE(){
				this.touchT = new Date().getTime();
			},
			//用户触摸结束事件
			touchendE(item) {
				this.touchE = new Date().getTime();
				//判断
				var timp = this.touchE - this.touchT
				if(timp >= 500){
					this.longtap()
				}else{
					this.userlistchlick(item)
				}
			},
			//添加好友
			confirm(){
				var T =false //是否有该好友了
				if(! uni.getStorageSync("user")){
					uni.$u.toast("登录后才能添加好友哦")
					return
				}else{
					if(JSON.parse(uni.getStorageSync("user")).id == this.keyword){
						uni.$u.toast("不能添加自己喔")
						return
					}
				}
				if(uni.getStorageSync("userfriendlist")){
					//遍历好友缓存查询是否有该好友
					var list = JSON.parse(uni.getStorageSync("userfriendlist"))
					for(var i = 0; i <list.length;i++){
						if(list[i].id == this.keyword){
							T = true
							uni.$u.toast('该用户以是您的好友了喔')
							return
						}
					}
				}
				if(!T){
					//获取缓存用户信息
					var user = uni.getStorageSync('user')
					var userid = 0
					var username = ""
					var userimg = ""
					var usersex = ""
					if(! user){
						uni.$u.toast("您还未登录")
						return
					}else{
						userid = JSON.parse(user).id
						username = JSON.parse(user).name
						userimg = JSON.parse(user).img
						usersex = JSON.parse(user).sex
					}
					var se = {
						sendUser:"",//发送用户
						sendUserName:"",//发送用户名
						sendUserImg:"",//发送用户头像
						receiveUser:"", //接收用户id
						messagecontent:"",//发送的信息
						isSystem:2//消息类型
					}
						se.sendUser= userid+":"+usersex
						se.sendUserName= username
						se.sendUserImg = userimg
						se.receiveUser= this.userInfo.id
						se.messagecontent = "请求添加好友"
						//发送信息
						app.globalData.websocket.sendMsg(se)
					this.show = false
				}
				
			},
			cancel(){
				console.log("取消")
				this.show = false
			},
			close(){
				this.show = false
			}
		}
	}
</script>

<style>
	@import url("../static/css/see.css");
</style>